package com.bootcamp.s2_0922.ds.Exercise._1004_Ex;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;

/**
 * @program: myClassCode
 * @description:
 * @author: Keyu Li
 * @create: 2021-10-04 19:43
 **/

public class Ex3_GuessNumber {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (!new Console().start())
                return;
        }
    }
}


class Console {
    private static final String PROPERTY_FILE = "gameRunCount.properties";
    private static Scanner scanner = new Scanner(System.in);
    private Properties gameCount;
    private int count;

    public Console() {
        this.gameCount = new Properties();
        try {
            gameCount.load(new FileInputStream(PROPERTY_FILE));
        } catch (IOException e) {
            count = 0;
            return;
        }
        count = Integer.parseInt(gameCount.getProperty("count"));
    }

    public boolean start() {
        if (count >= 5) {
            System.out.println("您可能是青少年防沉迷模式的受害者，已经到达最大游戏上限！");
            return false;
        }
        count++;
        System.out.println("---------Game Start----------");
        guessNumber();
        gameCount.setProperty("count", String.valueOf(count));
        try {
            gameCount.store(new FileOutputStream(PROPERTY_FILE), "No." + count + " game");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    private void guessNumber() {
        Random random = new Random();
        int rand = random.nextInt(100) + 1;
        System.out.print("random value created!\ninput an integer between 1~100: ");
        int countGuess = 0;
        while (true) {
            int userValue;
            try {
                userValue = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.print("please input a integer: ");
                continue;
            }
            countGuess++;
            if (userValue == rand) {
                System.out.println("Congratulations! you get "
                        + rand + " after " + countGuess + " guess!");
                break;
            } else if (userValue < rand) {
                System.out.print("input a larger number: ");
            } else {
                System.out.print("input a smaller number: ");
            }
        }
    }
}
